<?php
/**
 * @Description jwt组件
 * @Sonkwl Xiong
 * @Date 2022/01/07 13:47:45
 */
namespace Sonkwl\UsePHP;

Use \Sonkwl\UsePHP\mysqler;
Use \Sonkwl\UsePHP\jsoner;

class jwt{
    static private $keystr='WHSS';
    static private $keyint=7;
    static private $version="V1";//jwt版本
    static private $exp="";
    //DB验证配置
    static private $user_table="xczx.wh_user_t";
    static private $user_id="s_no";
    static private $user_name="s_name";
    static private $level_type='i_type';
    static private $level_table='xczx.whss_level_t';

    public static function SetKeyStr($str){
        self::$keystr=$str;
    }
    public static function SetKeyInt($inter){
        self::$keyint=$inter;
    }
    public static function SetVersion($v){
        self::$version=$v;
    }
    public static function SetExp($exp){
        self::$exp=$exp;
    }
    public static function SetUserTable($tbl){
        self::$user_table=$tbl;
    }
    public static function SetUserID($id){
        self::$user_id=$id;
    }
    public static function SetUserName($name){
        self::$user_name=$name;
    }
    public static function SetLevelTable($tbl){
        self::$level_table=$tbl;
    }
    public static function SetLevelType($t){
        self::$level_type=$t;
    }

    //@Sonkwl Xiong 2022/03/04 20:19:05
    //@Desc 设置jwt
    static public function Set($id){
        if(self::$exp==""){
            jsoner::Response(array("res"=>"NG","message"=>"exp没有定义，请使用SetExp"));
        }
        if(self::$version=="V1"){
            return self::SetJWTV1($id);
        }else{
            return self::SetJWT($id);
        }
    }
    //@Sonkwl Xiong 2022/03/04 20:19:22
    //@Desc 校验jwt
    static public function Check($token){
        if(self::$version=="V1"){
            return self::CheckJWTV1($token);
        }else{
            return self::CheckJWT($token);
        }
    }

    //@Sonkwl Xiong 2022/09/14 08:36:48
    //@Desc 验证token,需要在sonkwlphp框架下使用
    // level1为1级验证，level2为2级验证
    static public function Validate($token,$level1,$level2){
        if(!$tokenarray=self::Check($token)){
            return jsoner::Response(array("res"=>"NG","message"=>"token失效"));
        }
        if(isset($tokenarray["id"])){
            $val=$tokenarray["id"];
        }else{
            $val=$tokenarray[0];
        }
        //echo $val;
        //验证登录信息
        $s_admin_no=$val;
        $s_admin_name="";
        if($level1!=0){
            $db=mysqler::GetPDO();
            //验证登录信息
            $dbh=$db->prepare("select * from ".self::$user_table." where ".self::$user_id."=? limit 1;");
            $dbh->execute(array($val));
            $rs=$dbh->fetchAll(\PDO::FETCH_ASSOC);
            if(count($rs)==0){
                jsoner::Response(array("res"=>"NG","message"=>"用户资料异常，请重新登录"));
            }
            $s_admin_name=$rs[0][self::$user_name];
        }
        
        //获取用户权限
        $admin_level=array();
        if($level2!=0){
            $db=mysqler::GetPDO();
            $dbh=$db->prepare("select ".self::$level_type." from ".self::$level_table." where ".self::$user_id."=?;");
            $dbh->execute(array($val));
            $rs=$dbh->fetchAll(\PDO::FETCH_ASSOC);
            if(count($rs)==0){
                jsoner::Response(array("res"=>"NG","message"=>"用户权限异常"));
            }
            for($i=0;$i<count($rs);$i++){
                array_push($admin_level,$rs[$i][self::$level_type]);
            }
            if(!in_array($level2,$admin_level)){
                jsoner::Response(array("res"=>"NG","message"=>"您没有该模块的权限"));
            }
        }
        return array(
            "s_admin_no"=>$s_admin_no,
            "s_admin_name"=>$s_admin_name,
            "admin_level"=>$admin_level
        );
    }

    //@Sonkwl Xiong 2022/03/04 20:24:05
    //@Desc 获得id
    static public function Get($arr){
        if(self::$version=="V1"){
            return $arr[0];
        }else{
            return $arr["id"];
        }
    }

    //IHDS加密算法
	/*
	* $rInt操作权值，一般使用(可以自定义)：0:查询，1:新增，2:修改，3:删除，5:跨域验证,7:JWT
	*/
	static public function SetDoIHDS($string,$rInt)
	{
		$hex="";
		for($i=0;$i<strlen($string);$i++)
			$hex.=dechex(ord($string[$i])+$rInt);
		return $hex.$rInt.date("iHds");
	}
	//IHDS解密算法
	static public function GetDoIHDS($hex,$rInt)
	{   
		$t_hex=substr($hex,0,strlen($hex)-strlen($rInt.date("iHds")));
		$string=""; 
		for($i=0;$i<strlen($t_hex)-1;$i+=2)
			$string.=chr(hexdec($t_hex[$i].$t_hex[$i+1])-$rInt);
		return $string;
	}
    /**
     * JWT 版本V2
    */
    //生成jwt
    static public function SetJWT($id){
        $token='{"id":"'.$id.'","exp":"'.self::$exp.'","md5":"'.md5(self::$keystr.$id.self::$exp).'"}';
        $hex="";
        $token=self::SetDoIHDS($token,7);
        return $token;
    }
    //验证jwt
    static public function CheckJWT($token){
        //echo self::$keystr;
        $tstr=self::GetDoIHDS($token,7);
        $tokenarray=(array)json_decode($tstr,true);
        if(count($tokenarray)!=3 || $tokenarray["exp"]<time() || $tokenarray["md5"]!=md5(self::$keystr.$tokenarray["id"].$tokenarray['exp'])){
            return false;
        }
        return $tokenarray;
    }
    /**
     * JWT 版本V1
    */
    //生成jwt
    static public function SetJWTV1($id){
        $token=$id.'-'.self::$exp.'-'.md5(self::$keystr.$id.self::$exp);
        $hex="";
        $token=self::SetDoIHDS($token,self::$keyint);
        return $token;
    }
    //验证jwt
    static public function CheckJWTV1($token){
        $tstr=self::GetDoIHDS($token,self::$keyint);
        // echo $tstr;
        $tokenarray=explode('-',$tstr);
        // print_r($tokenarray);
        if(count($tokenarray)!=3 || $tokenarray[1]<time() || $tokenarray[2]!=md5(self::$keystr.$tokenarray[0].$tokenarray[1])){
            return false;
        }
        return $tokenarray;
    }
}
?>